package thread.producerAndconsumer;

/**
 * 一个生产者和消费者模型(生产者和消费者共用锁)
 * 仓库[即共享数据区域】
 *
 * @author ganbo
 * @date 2022/10/29 9:55
 */
public class SyncStack {

    private String[] strArray = new String[10];
    private int index;

    public synchronized void push(String str) throws InterruptedException {
        while (index >= strArray.length) {
            System.out.println("===============生产满了 =====================");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Thread.sleep(300);
        strArray[index] = str;
        ++index;

        System.out.println("生产了：--->" + str);
        notify();
    }

    public synchronized String pop() throws InterruptedException {
        while (index <= 0) {
            System.out.println("===============消费完了 =====================");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Thread.sleep(100);
        index--;
        notify();
        System.out.println("消费了============>" + strArray[index]);
        return strArray[index];
    }

    public String[] getStrArray() {
        return strArray;
    }


    public static void main(String[] args) {

        SyncStack syncStack = new SyncStack();

        //生产者
        for (int i = 0; i < 15; i++) {
            int finalI = i;
            new Thread(() -> {
                String str = "产品" + finalI;
                try {
                    syncStack.push(str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }


        //消费者
        for (int i = 0; i < 15; i++) {
            new Thread(() -> {
                String pop = null;
                try {
                    pop = syncStack.pop();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }


}
